/*
 * ChatView.java
 */
package client;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.InputMap;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 * The application's main frame.
 */
public class ChatView extends FrameView {

    private static final int CONNECTION = 0;
    private static final int DECONNECTION = 1;
    private static final int MESSAGE = 2;
    private static final int ERROR = 3;
    /**
     * Entete des messages
     */
    private Connection connection; // on cree un thread qui s'occupera de recevoir les entree venant du server
    private static HashSet<TextTab> vectTextTab = new HashSet();

    public ChatView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

        /**
         * on init le panel d'information, et on l'ajoute au vecteur
         */
        TextTab systemPanel = new TextTab(this, null, "systemPanel");
        tabPanel.addTab("System Panel", systemPanel);
        systemPanel.writeMessage("Welcome in this chat.\n you need to connect at one server");
        systemPanel.setEnsable(false);
        vectTextTab.add(systemPanel);
        
        /**
         * capte la fermeture par la crois dans la barre de la fenetre
         */
        JFrame mainFrame = ChatApp.getApplication().getMainFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void initConnection(String login, String host, int port) {
        // TODO code application logic here
        try {
            /*
             * creation de connection, entree sortie...
             */
            Socket socket = new Socket(host, port);
            OutputStream out = socket.getOutputStream();
            DataOutputStream sortie = new DataOutputStream(out);
            InputStream in = socket.getInputStream();
            DataInputStream entree = new DataInputStream(in);
            
            /*
             * envois d'un message au serveur pour l'avertir de la connexion
             * et du login du client
             */
            Message mess = new Message(CONNECTION, login, "server", login);
            mess.sendMessage(sortie);

            /*
             * on recois la reponse du serveur
             */
            mess.readMessage(entree);
            if (mess.getType() == ERROR) {
                // on l'ecrit dans le tab d'information du chat
                writeMessageTab(mess);
            } else {
                /*
                 * on cree la connection
                 * si le tab existe pas, on le cre
                 * on redefini les connection des tabs
                 * puis demarage du thread de la connection
                 */
                this.connection = new Connection(this, login, sortie, entree);
                if (!idTabExist(login)) {
                    TextTab newTab = new TextTab(this, connection, login);
                    tabPanel.addTab(login, newTab);
                    vectTextTab.add(newTab);
                }
                getTabClient(login).setConnection(connection);
                getTabClient("systemPanel").setConnection(connection);
                connectionMenuItem.setEnabled(false);
                deconnectionMenuItem.setEnabled(true);
                this.connection.start();
            }
        } catch (Exception e) {
            System.out.println("error " + e.toString());
        }
    }
    
    @Action
    public void closeConnection() {
        /**
         * si on est pas deconnecter, on previens le serveur qu'on vas le faire.
         */
        if (connection != null) {
            if (connection.closeConnection()) // on ferme le thread qui ecoute les entre
            {
                /**
                 * gestion de l'interface
                 */
                connectionMenuItem.setEnabled(true);
                deconnectionMenuItem.setEnabled(false);
            }
        }
    }

    @Action
    public void closeApplication() {
        try {
            closeConnection();
            System.exit(0); // fin de l'application client
        } catch (Exception e) {
        }
    }

    /*
     * redirige le message sur le tab identifie par le destinataire du tab
     */
    public void writeMessageTab(Message mess) {
        getTabClient(mess.getDest()).writeMessage(mess.getMessage());
    }

    /*
     * recupere le tab d'identifiant de idTab
     */
    public TextTab getTabClient(String idTab) {
        TextTab tabToReturn = null;
        for (TextTab textTab : vectTextTab) {
            if (idTab.equalsIgnoreCase(textTab.getIdTab())) {
                tabToReturn = textTab;
            }
        }
        return tabToReturn;
    }

    /*
     * revois vrai si l'idTab exist
     */
    private boolean idTabExist(String id) {
        boolean b = false;
        for (TextTab tab : vectTextTab) {
            if (id.equalsIgnoreCase(tab.getIdTab())) {
                b = true;
            }
        }
        return b;
    }


    public boolean isConnected() {
         return connection != null;
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ChatApp.getApplication().getMainFrame();
            aboutBox = new ChatAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ChatApp.getApplication().show(aboutBox);
    }

    @Action
    public void showQuitBox() {
        if (quitBox == null) {
            JFrame mainFrame = ChatApp.getApplication().getMainFrame();
            quitBox = new QuitBox(this, mainFrame, true);
        }
        ChatApp.getApplication().show(quitBox);
    }

    @Action
    public void showConnectionBox() {
        if (connectionBox == null) {
            JFrame mainFrame = ChatApp.getApplication().getMainFrame();
            connectionBox = new ConnectionBox(this, mainFrame, true);
        }
        ChatApp.getApplication().show(connectionBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        tabPanel = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        connectionMenuItem = new javax.swing.JMenuItem();
        deconnectionMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jSplitPane1.setName("jSplitPane1"); // NOI18N

        tabPanel.setName("tabPanel"); // NOI18N
        jSplitPane1.setRightComponent(tabPanel);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTree1.setName("jTree1"); // NOI18N
        jScrollPane1.setViewportView(jTree1);

        jSplitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(ChatView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(ChatView.class, this);
        connectionMenuItem.setAction(actionMap.get("showConnectionBox")); // NOI18N
        connectionMenuItem.setText(resourceMap.getString("connectionMenuItem.text")); // NOI18N
        connectionMenuItem.setToolTipText(resourceMap.getString("connectionMenuItem.toolTipText")); // NOI18N
        connectionMenuItem.setName("connectionMenuItem"); // NOI18N
        fileMenu.add(connectionMenuItem);

        deconnectionMenuItem.setAction(actionMap.get("closeConnection")); // NOI18N
        deconnectionMenuItem.setText(resourceMap.getString("deconnectionMenuItem.text")); // NOI18N
        deconnectionMenuItem.setEnabled(false);
        deconnectionMenuItem.setName("deconnectionMenuItem"); // NOI18N
        fileMenu.add(deconnectionMenuItem);

        exitMenuItem.setAction(actionMap.get("showQuitBox")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.setPreferredSize(new java.awt.Dimension(121, 19));
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenu1.setText(resourceMap.getString("editMenu.text")); // NOI18N
        jMenu1.setName("editMenu"); // NOI18N
        menuBar.add(jMenu1);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        jMenuItem1.setText(resourceMap.getString("documentationMenuItem.text")); // NOI18N
        jMenuItem1.setName("documentationMenuItem"); // NOI18N
        helpMenu.add(jMenuItem1);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 491, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        // TODO add your handling code here:
        //   QuitDialogBox dialogBox = new QuitDialogBox(null,true);
        //  dialogBox.setVisible(true);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem connectionMenuItem;
    private javax.swing.JMenuItem deconnectionMenuItem;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTree jTree1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTabbedPane tabPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private JDialog connectionBox;
    private JDialog quitBox;
}
